<!-- 离职面谈记录表 -->
<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew
        title="离职面谈记录表"
        :breadCrumb="['人事', '基础设置', '离职设置', '离职面谈记录表']"
        show-back
      ></pageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <!-- <a-select
          :style="{ width: '120px' }"
          placeholder="请选择"
          v-model="currScope"
          @change="onSearch"
        >
          <a-option :value="1">审核中</a-option>
          <a-option :value="2">审核后</a-option>
          <a-option :value="3">全部</a-option>
        </a-select> -->
        <a-input-search
          :style="{ width: '320px' }"
          placeholder="请输入记录表名称"
          search-button
          v-model="searchVal"
          @search="onSearch"
        >
          <template #button-icon>
            <icon-search />
          </template>
        </a-input-search>
      </template>
      <template #right>
        <a-button type="primary" @click="add(null)">新增记录表 </a-button>
        <a-button type="outline" @click="remove(null)" status="danger"
          >批量删除</a-button
        >
      </template>
    </ConditionBox>
    <TableTurn
      ref="tableRef"
      :tableData="getData"
      style="margin-top: 20px"
      :args="args"
    >
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        align="center"
        :width="200"
        title="离职面谈记录表名称"
        data-index="name"
      ></a-table-column>
      <!-- <a-table-column
        align="center"
        :width="100"
        title="适用范围"
        data-index="scope"
      >
        <template #cell="{ record }">
          <a-tag
            class="scope"
            :color="
              record.scope === 1
                ? `rgb(var(--green-1))`
                : 'rgb(var(--warning-1))'
            "
            :style="{
              color:
                record.scope === 1
                  ? `rgb(var(--green-6))`
                  : 'rgb(var(--warning-6))',
              '--scope':
                record.scope === 1
                  ? `rgb(var(--green-6))`
                  : 'rgb(var(--warning-6))'
            }"
          >
            {{ record.scope === 1 ? '审核中' : '审核后' }}
          </a-tag>
        </template>
      </a-table-column> -->
      <a-table-column
        align="center"
        :width="200"
        title="描述"
        data-index="remark"
      ></a-table-column>
      <a-table-column
        align="center"
        :width="100"
        title="启用状态"
        data-index="enable"
      >
        <template #cell="{ record }">
          <a-tag
            class="enable"
            :color="
              record.enable === 1
                ? `rgb(var(--green-1))`
                : 'rgb(var(--danger-1))'
            "
            :style="{
              color:
                record.enable === 1
                  ? `rgb(var(--green-6))`
                  : 'rgb(var(--danger-6))',
              '--enable':
                record.enable === 1
                  ? `rgb(var(--green-6))`
                  : 'rgb(var(--danger-6))'
            }"
          >
            {{ record.enable === 1 ? '启用' : '停用' }}
          </a-tag>
        </template>
      </a-table-column>
      <a-table-column
        align="center"
        :width="100"
        title="是否为默认"
        dataIndex="required"
      >
        <template #cell="{ record }">
          <a-switch
            :checked-value="1"
            :unchecked-value="2"
            v-model="record.required"
            @change="stateChange(record)"
          />
        </template>
      </a-table-column>
      <a-table-column align="center" title="操作" :width="100" fixed="right">
        <template #cell="{ record }">
          <a-space :size="0">
            <a-tooltip content="预览">
              <icon-eye
                size="26"
                @click="goPreview(record.id)"
                style="color: #5085ff; cursor: pointer"
              />
            </a-tooltip>
            <a-tooltip content="复制">
              <IconFont
                type="icon-fuzhi"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goCopy(record.id)"
              />
            </a-tooltip>
            <a-tooltip content="编辑">
              <IconFont
                type="icon-edit"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goEdit(record.id)"
              />
            </a-tooltip>
            <a-tooltip content="删除" position="left">
              <a-popconfirm
                content="是否确认删除该条数据?"
                position="left"
                @ok="remove(record)"
              >
                <IconFont
                  type="icon-delete"
                  :size="26"
                  :style="{
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </a-space>
        </template>
      </a-table-column>
    </TableTurn>
  </ContentCard>
  <!-- <a-modal
    title="选择记录表模板形式"
    v-model:visible="visible"
    @cancel="visible = false"
    :footer="false"
    title-align="center"
  >
    <div class="cardAll">
      <div class="caedStyle" @click="auditState(1)">审核中记录表</div>
      <div class="caedStyle" @click="auditState(2)">审核后记录表</div>
    </div>
  </a-modal> -->
  <TemplateDesign
    title="离职面谈记录表"
    ref="showTemplate"
    type="editShow"
    :id="fromData.data.id"
    :back="back"
    :template="templateDataShow"
    :hierarchy="2"
    @upshowData="upshowData"
    @sortshowData="sortshowData"
    :refForm="refForm"
    @save-form="save"
  >
    <template #base>
      <a-form
        ref="refForm"
        :rules="rules"
        :model="fromData.data"
        layout="vertical"
      >
        <a-form-item field="name" label="离职面谈记录表模板名称：" required>
          <a-input
            size="large"
            v-model="fromData.data.name"
            placeholder="请输入模板名称"
            allow-clear
          />
        </a-form-item>
        <!-- <a-form-item field="scope" label="适用范围" required>
          <a-input
            disabled
            size="large"
            v-model="fromData.data.scope"
            allow-clear
          />
        </a-form-item> -->
        <a-form-item field="state" label="启用状态">
          <a-switch
            v-model="fromData.data.enable"
            :checked-value="1"
            :unchecked-value="2"
          />
        </a-form-item>
        <a-form-item field="remark" label="描述">
          <a-textarea
            v-model="fromData.data.remark"
            placeholder="请输入"
            show-word-limit
            :max-length="300"
            :auto-size="{
              minRows: 5
            }"
            allow-clear
          />
        </a-form-item> </a-form
    ></template>
    <template #template-design>
      <DimissionTemplateDesign
        :problemData="problemData.data"
        @upData="upData"
      ></DimissionTemplateDesign>
    </template>
  </TemplateDesign>
  <PreviewModal v-model:visible="previewVisible" :data="currData.data" />
  <CopyModal
    v-model:visible="copyVisible"
    @copy-emit="copyEmit"
    @copyEditEmit="copyEditEmit"
    :validateFun="validateName"
  />
</template>
<script setup lang="ts">
import {
  GetLeaveInterviewList,
  GetLeaveInterviewDetail,
  PostLeaveInterviewDetail,
  DelLeaveInterviewList,
  DelLeaveInterviewTakeProblem,
  PutLeaveInterviewDetail,
  PutLeaveInterviewTakeShow,
  PutLeaveInterviewTemplate,
  RepeatLeaveInterviewList
} from '@/apis/management/human/baseSetting/leaveSetting';
import { Message, Modal } from '@arco-design/web-vue';
import clonedeep from 'lodash.clonedeep';
import { GetBusinessModalData } from '@/apis/controltotal/index';
import DimissionTemplateDesign from './Components/TemplateDesign/index.vue';
import { changeControlData } from '@/utils/control';
import { validateRules } from '@/utils/common';
import PreviewModal from './Components/Preview/index.vue';

let tableRef = ref(); // 储存表格的ref
let searchVal = ref(''); // 输入框的值
let currScope = ref(3); // 下拉框值
let visible = ref(false); // 新增弹窗显示
let showTemplate = ref(); // Template显示
const refForm = ref();
// 表格配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
});
const problemData: any = reactive({ data: [] });
const fromData = reactive<any>({
  data: {
    name: '',
    enable: 1,
    remark: '',
    scope: '审核中',
    collections: [],
    takes: []
  }
});
const templateData: any = reactive({ data: [] });
const init = async () => {
  const res = await GetBusinessModalData({
    funcCode: 'SER_FUNC3803005BBBBA4640A9CEDACFB599C3C3'
  });
  templateData.data = res?.funcCtlInfos
    ? changeControlData(res.funcCtlInfos, 'subDetail')
    : null;
};

const templateDataShow = computed(() => {
  if (fromData.data.collections.length === 0) {
    templateData.data.forEach((ele: any) => {
      ele.subRelDetail.forEach((item: any) => {
        item.show = true;
      });
    });
    return templateData.data;
  } else {
    console.log(1);
    const data = clonedeep(templateData.data);
    const ids: string[] = [];
    const subId: number[] = [];
    const idsShow: { show: number; id: number; hid: number }[] = [];
    fromData.data.collections.forEach((ele: any) => {
      subId.push(ele.id);
      ele.controls.forEach((item: any) => {
        ids.push(item.ctlCode + item.subsetId);
        // idsShow[item.ctlCode + item.subsetId] = item.show;
        idsShow.push({ id: item.id, show: item.show, hid: ele.id });
      });
    });
    data.forEach((ele: any, index: number) => {
      ele.id = subId[index];
      ele.subRelDetail.forEach((item: any) => {
        if (ids.indexOf(item.ctlCode + item.subsetId) !== -1) {
          item.show =
            idsShow[ids.indexOf(item.ctlCode + item.subsetId)].show === 1
              ? true
              : false;
          item.id = idsShow[ids.indexOf(item.ctlCode + item.subsetId)].id;
          item.hid = idsShow[ids.indexOf(item.ctlCode + item.subsetId)].hid;
        }
      });
    });
    return data;
  }
});

init();
/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
const selectedListData = computed(() => tableRef.value.selectedListData);

// 获取表格数据
const getData = async (pageData: any) => {
  try {
    const res = await GetLeaveInterviewList({
      ...pageData,
      name: searchVal.value
    });
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

// 点击搜索按钮
const onSearch = () => {
  refresh();
};

// 监听键盘回车，按了回车也会查询
const keyDown = (e: any) => {
  if (e.keyCode === 13) {
    tableRef.value.loadData();
  }
};

onMounted(() => {
  // 监听键盘事件
  window.addEventListener('keydown', keyDown);
});

// 修改设为默认的状态
const stateChange = async (record: any) => {
  try {
    //PutLeaveInterviewTakeDefault
    await PutLeaveInterviewTemplate({ id: record.id, scope: record.scope });
    refresh();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 点击编辑按钮
const goEdit = async (id: number, name?: string) => {
  const res: any = await GetLeaveInterviewDetail({ id });
  Object.assign(fromData.data, res);
  rulesEdit.data.name = res.name;
  rulesEdit.data.edit = true;
  if (name) {
    fromData.data.name = name;
    delete fromData.data.id;
    delete fromData.data.createdAt;
  }
  console.log('goEdit', res, rulesEdit.data);
  problemData.data = clonedeep(fromData.data.takes);
  showTemplate.value.fullScreen();
};

// 批量删除
const remove = async (record: any | null) => {
  try {
    if (!record) {
      if (selectedList.value.length === 0) {
        Message.error('请至少选择一项！');
      } else {
        Modal.confirm({
          title: '提示',
          content: '确定要删除选中的数据吗？',
          onOk: async () => {
            try {
              if (
                selectedListData.value.find((item: any) => item.required === 1)
              ) {
                Message.error('默认模板不能删除！');
              } else {
                await DelLeaveInterviewList({
                  ids: selectedList.value
                });
                tableRef.value.selectedList = [];
                refresh();
              }
            } catch (error: unknown) {
              console.log(error);
            }
          }
        });
      }
    } else {
      if (record.required === 1) Message.error('默认模板不能删除！');
      else {
        await DelLeaveInterviewList({
          ids: [record.id]
        });
        tableRef.value.selectedList = [];
        refresh();
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 刷新表格数据
const refresh = () => {
  tableRef.value.loadData();
};
// 更新控件
const upshowData = async (e: any) => {
  const pending: string[] = [];
  const pendingState: { id: string; show: boolean }[] = [];
  const ids: { id: number; show: number; hid: number }[] = [];
  e.forEach((ele: any) => {
    console.log('ele', ele, fromData.data.collections);
    if (ele.id) ids.push({ id: ele.id, show: ele.show ? 1 : 2, hid: ele.hid });
    pending.push(ele.subsetId + ele.ctlCode);
    pendingState.push({ id: ele.subsetId + ele.ctlCode, show: ele.show });
  });
  templateData.data.forEach((ele: any) => {
    ele.subRelDetail.forEach((item: any) => {
      if (pending.indexOf(item.subsetId + item.ctlCode) !== -1) {
        item.show =
          pendingState[pending.indexOf(item.subsetId + item.ctlCode)].show;
      }
    });
  });
  if (ids.length != 0) {
    fromData.data.collections.forEach((ele: any) => {
      ele.controls.forEach((item: any) => {
        if (pending.indexOf(item.subsetId + item.ctlCode) !== -1) {
          item.show = pendingState[
            pending.indexOf(item.subsetId + item.ctlCode)
          ].show
            ? 1
            : 2;
        }
      });
    });
    await PutLeaveInterviewTakeShow({ controls: ids });
    refresh();
  }
};
// 更新面谈问题记录
const upData = async (e: any) => {
  console.log('data', e);
  if (e.type === 1) {
    e.data.forEach((ele: any) => {
      problemData.data.push(ele);
    });
    // problemData.data = e.data;
  } else if (e.type === 2) {
    e.data.hid = fromData.data?.id;
    if (e.data.id) {
      problemData.data.forEach((ele: any) => {
        if (ele.id === e.data.id) {
          ele.problem = e.data.problem;
        }
      });
    } else if (e.data.index) {
      console.log('e.data.index', e.data.index);
      problemData.data.forEach((ele: any, index: number) => {
        if (index + 1 === e.data.index) {
          console.log('datasadsad', ele);
          ele.problem = e.data.problem;
        }
      });
    } else {
      problemData.data.push(clonedeep(e.data));
    }
  }
  if (e.type === 3) {
    if (e.data.id) {
      await DelLeaveInterviewTakeProblem({ ids: [e.data.id] });
      problemData.data.splice(e.data.index, 1);
    } else {
      problemData.data.splice(e.data.index, 1);
    }
  }
};
// 控件排序
const sortshowData = (e: any) => {
  templateData.data[e.index].subRelDetail = e.data;
};
// 审核
const auditState = (type: number) => {
  if (type === 1) {
    fromData.data.scope = '审核中';
  } else {
    fromData.data.scope = '审核后';
  }
  showTemplate.value.fullScreen();
};

const add = (data: any | null) => {
  showTemplate.value.fullScreen();
};

// 保存
const save = async () => {
  if (fromData.data.name === '') {
    Message.error('模板名不能为空');
    return 2;
  }

  fromData.data.takes = clonedeep(problemData.data);

  if (fromData.data.id) {
    await PutLeaveInterviewDetail(fromData.data);
  } else {
    fromData.data.collections = clonedeep(templateData.data);
    fromData.data.collections.forEach((ele: any) => {
      ele.name = ele.cnName;
      ele.controls = ele.subRelDetail;
      ele.controls.forEach((item: any) => {
        item.show ? (item.show = 1) : (item.show = 2);
      });
    });
    await PostLeaveInterviewDetail(fromData.data);
  }
  fromData.data = {
    name: '',
    enable: 1,
    remark: '',
    collections: [],
    takes: []
  };
  problemData.data = [];

  rulesEdit.data.name = '';
  rulesEdit.data.edit = false;
  visible.value = false;
  refresh();
};
// 取消
const back = () => {
  fromData.data = {
    name: '',
    enable: 1,
    remark: '',
    collections: [],
    takes: []
  };
  problemData.data = [];
  rulesEdit.data.name = '';
  rulesEdit.data.edit = false;
  visible.value = false;
};

const rulesEdit = reactive({ data: { edit: false, name: '' } });
const rules = {
  name: [
    {
      required: true,
      message: '请输入'
    },
    {
      validator: async (value: string, cb: any) => {
        try {
          if (rulesEdit.data.edit && value === rulesEdit.data.name) {
            return;
          } else {
            const res = await RepeatLeaveInterviewList({
              name: value
            });
            if (res.code) cb(`${res.msg}`);
          }
        } catch (error: any) {
          console.log(error);
        }
      }
    }
  ]
};

let previewVisible = ref(false);
const goPreview = async (id: number) => {
  try {
    currData.data = await GetLeaveInterviewDetail({ id });
    previewVisible.value = true;
  } catch (error: any) {
    console.log(error);
  }
};

let copyVisible = ref(false);
let currId = ref(0);
let currData = reactive({
  data: {}
});

// 模板查重函数
const validateName = async (name: string) => {
  try {
    if (name === currData.data.name && currData.data.id) {
      //
    } else {
      const data = {
        name
      };
      const res = await validateRules(RepeatLeaveInterviewList, data);
      return Promise.resolve(res);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};
// 显示复制弹窗
const goCopy = (id: number) => {
  currId.value = id;
  copyVisible.value = true;
};

// @typescript-eslint/no-unused-vars
const copyEmit = async (formData: any) => {
  try {
    const res: any = await GetLeaveInterviewDetail({ id: currId.value });
    Object.assign(fromData.data, res);
    fromData.data.name = formData.name;
    delete fromData.data.id;
    delete fromData.data.createdAt;
    fromData.data.takes = fromData.data.takes.map((el: any) => {
      return {
        problem: el.problem
      };
    });
    await PostLeaveInterviewDetail(fromData.data);
    refresh();
  } catch (error: any) {
    console.log(error);
  }
};

// 复制弹窗点击确认并编辑
const copyEditEmit = (formData: any) => {
  goEdit(currId.value, formData.name);
};
</script>
<style lang="less" scoped>
.wrap {
  padding: 10px 20px;
  .header {
    display: flex;
    justify-content: space-between;
  }
}
.cardAll {
  display: flex;
  flex-direction: column;
  // justify-content: center;
  align-items: center;
  .caedStyle {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 80px;
    width: 400px;
    font-size: 22px;
    // font-weight: 600;
    margin-bottom: 20px;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
  }
}
.caedStyle:hover {
  color: #538dff;
  cursor: pointer;
  box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.5);
}
.enable::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: relative;
  right: 3px;
  background-color: var(--enable);
}

.scope::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: relative;
  right: 3px;
  background-color: var(--scope);
}
</style>
